﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using UnityEngine.UI;
using UnityEngine.Video;

public class VideoOperator : MonoBehaviour {

	public GameObject goUI = null;

	public GameObject goVideoFirst = null;
	public GameObject goVideoSecond = null;


	public AudioSource bgm = null;

	public DragObj dragObj = null;

	public VideoPlayer vpFirst = null;
	public VideoPlayer vpSecond = null;

	public VideoCfgData.VideoCfg cfg = null;

	public GameObject menu = null;
    public GameObject nextVideo = null;
	public GameObject btnback = null;
	public GameObject btnReplay = null;
	public GameObject btnPlay = null;
    public GameObject btnPause = null;
    //	public Button realbtnGoon = null;


    // new ui
    public GameObject menuIng = null;
    public GameObject menuOver = null;
    public GameObject menuChose = null;
    public Button btnIngPause = null;
    public Button btnIngPlay = null;
    public GameObject btnIngOver = null;

    public GameObject manbanjiezou = null;
    public GameObject manbanjiezouPause = null;
    public AudioSource manbanjiezouAudiosource = null;
    public GameObject btnManbanjiezou = null;
    // new ui end

    public AudioClip audioClip1 = null;
	public AudioClip audioClip2 = null;


    private string lessonKey = "";
    public bool IsQiaoqiaodada()
    {
        if (lessonKey == "qiaoda")
            return true;
        else
            return false;
    }

	private static VideoOperator instance = null;
	public static VideoOperator GetInstance ()
	{
		return instance;
	}

    /*	public void Init( string id )
        {
            vpFirst.prepareCompleted -= BeginPlay;

            cfg = DataManager.videoCfgData.GetCfg (id);
            if (cfg == null)
                return;

            goVideoFirst.SetActive (true);
            vpFirst.url = ResLoader.Url2LocalPath (cfg.urlVideo1);


            if (cfg.VideoType == "multi") {

                vpSecond.url = ResLoader.Url2LocalPath (cfg.urlVideo2);
                dragObj.Init ( cfg.urlImage ,cfg.size, cfg.beginPos, cfg.endPos, OnSwitchVideo);
            }


            // 准备音频
            audioClip1 = null;
            audioClip2 = null;
            bgm.clip = null;

            if (string.IsNullOrEmpty (cfg.urlAudio1) && string.IsNullOrEmpty (cfg.urlAudio2))
                Begin ();
            else {

                if (!string.IsNullOrEmpty (cfg.urlAudio1) && cfg.urlAudio1 != "0") {
                    ResLoader.Load(cfg.urlAudio1, null, (www)=>{



                        audioClip1 = WWWAudioExtensions.GetAudioClip (www);

                        if ( string.IsNullOrEmpty (cfg.urlAudio2) )
                            Begin();
                        else if ( audioClip2 != null )
                            Begin();
                    }, true, true);
                }
                if (!string.IsNullOrEmpty (cfg.urlAudio2) && cfg.urlAudio2 != "0") {
                    ResLoader.Load(cfg.urlAudio2, null, (www)=>{


                        audioClip2 = WWWAudioExtensions.GetAudioClip (www);

                        if ( string.IsNullOrEmpty (cfg.urlAudio1) )
                            Begin();
                        else if ( audioClip1 != null )
                            Begin();
                    }, true, true);
                }

            }


        }
    */


    public void Init(string id, string key )
    {

        cfg = DataManager.videoCfgData.GetCfg(id);
        if (cfg == null)
            return;

        lessonKey = key;
        if (!IsQiaoqiaodada())
            btnManbanjiezou.SetActive(false);
        else
            btnManbanjiezou.SetActive(true);

        goUI.SetActive(false);
        menu.SetActive(false);
        menuIng.SetActive(false);
        

        goVideoFirst.SetActive(true);
        vpFirst.url = ResLoader.Url2LocalPath(cfg.urlVideo1);


        if (cfg.VideoType == "multi"&& !string.IsNullOrEmpty( cfg.GetVideoKuaisu()) )
        {

            vpSecond.url = ResLoader.Url2LocalPath(cfg.GetVideoKuaisu());
            string urlA2 = cfg.GetAudioKuaisu();
            if ( !string.IsNullOrEmpty(urlA2) )
            {
                ResLoader.Load(urlA2, null, (www) =>
                {
                    audioClip2 = WWWAudioExtensions.GetAudioClip(www);
                }, true, true);
            }


            // 有图标时，初始化拖动
            if (NeedToDrag())
                dragObj.Init(cfg.urlImage, cfg.size, cfg.beginPos, cfg.endPos, OnSwitchVideo);
        }


        // 准备音频
        audioClip1 = null;
        bgm.clip = null;

        if (string.IsNullOrEmpty(cfg.urlAudio1))
            Begin();
        else
        {

            if (!string.IsNullOrEmpty(cfg.urlAudio1) && cfg.urlAudio1 != "0")
            {
                ResLoader.Load(cfg.urlAudio1, null, (www) => {

                    audioClip1 = WWWAudioExtensions.GetAudioClip(www);
                    Begin();
                }, true, true);
            }
        }


    }

    void Awake()
	{
		instance = this;

	}

	// Use this for initialization
	void Start () {

        vpFirst.sendFrameReadyEvents = true;
        vpFirst.frameReady += VideoFrameCallback;
        vpSecond.sendFrameReadyEvents = true;
        vpSecond.frameReady += VideoFrameCallback;

        vpFirst.loopPointReached += OnEndVideoPlay;
		vpSecond.loopPointReached += OnEndVideoPlay;

        vpFirst.prepareCompleted += BeginPlay;
        vpSecond.prepareCompleted += SecondBeginPlay;

        goUI.SetActive (false);

	}

    void VideoFrameCallback( VideoPlayer v, long frameIdx )
    {

        if ( v == vpFirst )
        {
            if (cfg.interactive1 > 0 && frameIdx == cfg.interactive1 )
            {
                Debug.Log("framecallback to the interactive1:" + cfg.interactive1);
                // vpfirst
                vpFirst.Pause();
                if (bgm.isPlaying)
                    bgm.Pause();

                nowvp = vpFirst;
                nowas = bgm;

                // 对音频定位纠正
                bgm.time = (float)vpFirst.time;
                Debug.Log("bgm time:" + bgm.time);

                // btn next video
                menu.SetActive(false);
                nextVideo.SetActive(true);


                // 还有新的menu
                OnCloseMenuing();

                Debug.Log("first videoplayer frame callback . frameidx=" + frameIdx +" nextVideo set true");


            }
        }
        else if ( v == vpSecond )
        {
            if (cfg.interactive2 > 0 && frameIdx == cfg.interactive2 )
            {
                // vpsecond
                vpSecond.Pause();
                if (bgm.isPlaying)
                    bgm.Pause();

                nowvp = vpSecond;
                nowas = bgm;

                // btn next video
                menu.SetActive(false);
                nextVideo.SetActive(true);

                Debug.Log("second videoplayer frame callback . frameidx=" + frameIdx + " nextVideo set true");
            }
        }

    }
	
	// Update is called once per frame
	void Update () {

	}

	void HideAll()
	{
		goUI.SetActive (false);
		goVideoFirst.SetActive (false);
		goVideoSecond.SetActive (false);
		menu.SetActive (false);
	}


	public void Begin()
	{
		

		goUI.SetActive (false);
		goVideoSecond.SetActive (false);
		menu.SetActive (false);

		btnPlay.SetActive (true);
//		realbtnGoon.interactable = true;


//		vpFirst.Play ();
//		playBgm (audioClip1);
//		Loading.GetInstance ().EndLoading ();

		
		vpFirst.Prepare ();

	}

    public void BeginPlay(VideoPlayer vp)
	{
        Debug.Log("prepare finished");
		vp.Play ();

		playBgm (audioClip1);
		Loading.GetInstance ().EndLoading ();
	}

    public void SecondBeginPlay(VideoPlayer vp)
    {
        Debug.Log("into secondBeginPlay");
        vp.Play();
        playBgm(audioClip2);

        menuChose.SetActive(false);
        Loading.GetInstance().EndLoading();
    }

    

    public void playBgm(AudioClip ac)
	{

		if ( ac == null )
			return;

		bgm.clip = ac;
//        bgm.Stop();
        bgm.time = 0;
		bgm.Play ();

	}

	public void OnSwitchVideo()
	{
		// switch
		Debug.Log( "onSwitchVideo...." );

        goUI.SetActive(false);

        OnMenuchoseKuaisu();

        

        /*        
                goVideoSecond.SetActive (true);
                vpSecond.Play ();

                playBgm (audioClip2);*/

    }

    bool NeedToDrag()
    {
        if (cfg.VideoType == "multi" && !string.IsNullOrEmpty(cfg.urlImage))
            return true;

        return false;
    }

	void OnEndVideoPlay( VideoPlayer vp )
	{
		if (cfg.VideoType == "single") {
		
			EndOpenMenu ();
		} else {
		
			if (vp == vpFirst) {


                // 鼓皮

                //				goUI.SetActive (true);
                //                menuOver.SetActive(true);


                // 有图标就显示拖动UI，没有直接跳转下一个视频
                if ( NeedToDrag() )
                    goUI.SetActive(true);
                else
                    OnMenuchoseKuaisu();


            } else {

				EndOpenMenu ();
			}
		}
			


	}

    public void OnBtnNextVideo()
    {

        Debug.Log("on btn next video");

        nextVideo.SetActive(false);

        nowas.Play();
        nowvp.Play();
//        OnSwitchVideo();
    }

	public void OnBtnBack()
	{

		bgm.Stop ();

        btnIngPause.gameObject.SetActive(true);
        btnPause.SetActive(true);

		lessonUI.GetInstance ().ShowLessonInfo ();
	}

	public void OnBtnGoon()
	{
		if (nowvp != null)
			nowvp.Play ();

		if (nowas != null)
			nowas.Play ();

		menu.SetActive (false);
	}

	public void OnBtnReplay()
	{

//		goVideoSecond.SetActive (false);

//		playBgm (audioClip1);

//		vpFirst.time = 0;
//		vpFirst.Play ();

//		btnPlay.SetActive (true);
//        btnPause.SetActive(true);


		menu.SetActive (false);
        btnPause.SetActive(true);

        if ( goVideoSecond.activeSelf )
        {
            vpSecond.Stop();
            vpSecond.Play();
            bgm.Stop();
            bgm.time = 0;
            bgm.Play();
        }
        else
        {
            vpFirst.Stop();
            vpFirst.Play();
            bgm.Stop();
            bgm.time = 0;
            bgm.Play();
        }

	}


	VideoPlayer nowvp = null;
	AudioSource nowas = null;
	public void OnOpenMenu()
	{
        Debug.Log("on open menu");
		if ( menu.activeSelf )
		{

            if ((cfg.VideoType == "single" && vpFirst.frameCount - (ulong)vpFirst.frame <= 1) || (cfg.VideoType == "multi" && vpSecond.frameCount - (ulong)vpSecond.frame <= 1))
                return;

            // 排除播放完成的情况
            menu.SetActive(false);
            return;

		}
        else if ( menuIng.activeSelf )
        {
            menuIng.SetActive(false);
            return;
        }
//        else if ( menuOver.activeSelf)
//        {
//            menuOver.SetActive(false);
//            return;
//        }
        

		nowvp = null;
		nowas = null;

        int playingIdx = 1;
        bool isPlaying = false;

		if (vpFirst.gameObject.activeSelf && vpFirst.isPlaying )
        {
            nowvp = vpFirst;
            isPlaying = true;
        }

		else if (vpSecond.gameObject.activeSelf && vpSecond.frameCount - (ulong)vpSecond.frame > 1)
        {
            nowvp = vpSecond;
            playingIdx = 2;

        }


		if (bgm.isPlaying)
			nowas = bgm;

/*		if (cfg.VideoType != "multi") {

			if ( nowvp != null )
				nowvp.Pause ();

			if (nowas != null )
				nowas.Pause ();
		}*/

        if ( playingIdx == 2 )
		    menu.SetActive (true);
        else
        {

                // 打开播放中的菜单
                menuIng.SetActive(true);
            if (cfg.interactive1 > 0 && vpFirst.frame < cfg.interactive1 )
                btnIngOver.SetActive(true);
            else
                btnIngOver.SetActive(false);

        }


        /*
			if (cfg.VideoType == "single") {
		
				btnback.SetActive (true);
				btnGoon.SetActive (true);
				btnReplay.SetActive (true);
			} else {
		
				btnback.SetActive (true);
				btnGoon.SetActive (false);
				btnReplay.SetActive (false);
			}*/

        btnback.SetActive(true);
        btnPlay.SetActive(true);
        btnReplay.SetActive(true);

    }

	public void EndOpenMenu()
	{
        // ios下某些音频长度定位错误，会播放不存在的长度导致杂音，此处关闭
        bgm.Stop();

		menu.SetActive (true);
		btnback.SetActive (true);
		btnPlay.SetActive (false);
		btnReplay.SetActive (true);
        menuIng.SetActive(false);


        if (string.IsNullOrEmpty( cfg.GetAudioMansu() ) || !IsQiaoqiaodada() )
        {
            btnManbanjiezou.SetActive(false);
        }
        else
        {
            btnManbanjiezou.SetActive(true);
        }

//		realbtnGoon.interactable = false;
	}

    void OnApplicationPause(bool pause)
    {
        // 回到桌面
        if(pause)
        {
            if (vpFirst.isPlaying)
                nowvp = vpFirst;
            else if (vpSecond.isPlaying)
                nowvp = vpSecond;
            if (bgm.isPlaying)
                nowas = bgm;

            nowvp.Pause();
            nowas.Pause();

            Debug.Log("pause the as");
        }
    }

    void OnApplicationFocus(bool focus)
    {
        // 返回游戏
        if (focus)
        {
            if (nowvp != null)
            {
                nowvp.Play();

                if (nowas != null )
                {
                    nowvp.started += OnStartedVideoplayerForPlayAudio;
                }
            }



            Debug.Log("play the vp");
        }
    }

    private void OnStartedVideoplayerForPlayAudio(VideoPlayer v)
    {
        nowas.Play();
        nowvp.started -= OnStartedVideoplayerForPlayAudio;

        Debug.Log("play the as");

    }

    public void OnCloseMenuing ()
    {
        menuIng.SetActive(false);
    }

    public void OnCloseMenuover()
    {
        menuOver.SetActive(false);
    }

    public void OnMenuingPause()
    {
        vpFirst.Pause();
        bgm.Pause();

        btnIngPause.gameObject.SetActive(false);
    }

    public void OnMenuingPlay()
    {
        vpFirst.Play();
        bgm.Play();

        btnIngPause.gameObject.SetActive(true);
    }

    public void OnMenuingNext()
    {
        OnCloseMenuing();

        vpFirst.Pause();
        bgm.Pause();

        //OnMenuchoseKuaisu();
        JumpToFrame(vpFirst, cfg.interactive1);


        
    }

    public void JumpToFrame( VideoPlayer vp, int idx )
    {
        vp.Pause();
        vp.frame = idx;

        Debug.Log("jump to frame :" + idx + "      intera=" + cfg.interactive1 + "     vp.framecount=" + vp.frameCount);        


        bgm.Pause();

        nowvp = vp;
        nowas = bgm;

        // 对音频定位纠正
        bgm.time = idx / vp.frameRate;
        Debug.Log("bgm time:" + bgm.time);

        // btn next video
        menu.SetActive(false);
        nextVideo.SetActive(true);


        // 还有新的menu
        OnCloseMenuing();


        btnIngPause.gameObject.SetActive(true);
        

    }

    public void OnMenuoverNext()
    {
        OnCloseMenuover();

        //        menuChose.SetActive(true);
        OnMenuchoseKuaisu();
    }

    public void OnMenuoverReplay()
    {
        vpFirst.Stop();
        bgm.Stop();

        vpFirst.Play();
        bgm.Play();

        menuOver.SetActive(false);

    }

    public void OnMenuchoseMansu()
    {
        

        string urlV = cfg.GetVideoMansu();
        string urlA = cfg.GetAudioMansu();
        if (urlV == null)
            return;

        goVideoSecond.SetActive(true);

        vpSecond.url = ResLoader.Url2LocalPath(urlV);

        // 准备音频
        audioClip2 = null;
        bgm.clip = null;

        if (string.IsNullOrEmpty(urlA))
            vpSecond.Prepare();
        else
        {

            if (!string.IsNullOrEmpty(urlA) && urlA != "0")
            {
                ResLoader.Load(urlA, null, (www) =>
                {

                    audioClip2 = WWWAudioExtensions.GetAudioClip(www);
                    vpSecond.Prepare();
                }, true, true);
            }
        }
    }

    public void OnMenuchoseKuaisu()
    {


        string urlV = cfg.GetVideoKuaisu();
        string urlA = cfg.GetAudioKuaisu();
        if (urlV == null)
            return;

        // 隐藏拖动物品
        goUI.SetActive(false);

        OnCloseMenuing();

        goVideoFirst.SetActive(false);
        goVideoSecond.SetActive(true);



        /*
        vpSecond.url = ResLoader.Url2LocalPath(urlV);

        // 准备音频
        audioClip2 = null;
        bgm.clip = null;

        if (string.IsNullOrEmpty(urlA))
            vpSecond.Prepare();
        else
        {

            if (!string.IsNullOrEmpty(urlA) && urlA != "0")
            {
                ResLoader.Load(urlA, null, (www) =>
                {

                    audioClip2 = WWWAudioExtensions.GetAudioClip(www);
                    vpSecond.Prepare();
                }, true, true);
            }
        }*/

        vpSecond.Prepare();
    }


    public void OnBtnOpenManbanjiezou()
    {
        vpSecond.Pause();
        bgm.Pause();

        manbanjiezou.SetActive(true);
        manbanjiezouPause.SetActive(true);

        string urlA = cfg.GetAudioMansu();
        ResLoader.PlayAudio(manbanjiezouAudiosource, urlA);
    }

    public void OnBtnCloseManbanjiezou()
    {
        manbanjiezou.SetActive(false);
        btnPause.SetActive(false);
    }

    public void OnBtnManbanjiezouReplay()
    {
        manbanjiezouAudiosource.Stop();
        manbanjiezouAudiosource.Play();
    }

    public void OnBtnManbanjiezouPlay()
    {
        manbanjiezouAudiosource.Play();
        manbanjiezouPause.SetActive(true);
    }

    public void OnBtnManbanjiezouPause()
    {
        manbanjiezouAudiosource.Pause();
        manbanjiezouPause.SetActive(false);
    }


    public void OnBtnMenuPlay()
    {
        vpSecond.Play();
        bgm.Play();
        btnPause.SetActive(true);
    }

    public void OnBtnMenuPause()
    {
        vpSecond.Pause();
        bgm.Pause();
        btnPause.SetActive(false);
    }
}
